<?php

class UserTokenBehavior extends CActiveRecordBehavior
{
    public function getUserIdByToken($access_token)
    {
        $result = 0;
        if (empty($access_token)) {
            return $result;
        }
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('access_token' => $access_token));
        $item = $this->getOwner()->find($criteria);
        if (!is_null($item)) {
            $result = $item->user_id;
        }
        return $result;
    }

    public function getTokenByUserId($user_id, $app_id = 0)
    {
        $result = '';
        if (empty($user_id)) {
            return $result;
        }
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        if (!empty($app_id)) {
            $criteria->addColumnCondition(array('client_id' => $app_id));
        }
        $item = $this->getOwner()->find($criteria);
        if (!is_null($item)) {
            $result = $item->access_token;
        }
        return $result;
    }

    public function getByUserId($user_id, $app_id = 0)
    {
        $result = 0;
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        if (!empty($app_id)) {
            $criteria->addColumnCondition(array('client_id' => $app_id));
        }
        $item = $this->getOwner()->find($criteria);
        if (!is_null($item)) {
            $result = $item;
        }
        return $result;
    }

    public function getPlatformByUserId($user_id, $app_id = 0)
    {
        $result['push_user_id'] = '';
        $result['platform'] = '';
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        if (!empty($app_id)) {
            $criteria->addColumnCondition(array('client_id' => $app_id));
        }
        $item = $this->getOwner()->find($criteria);
        if (!is_null($item)) {
            $result['push_user_id'] = $item->user_push_id;
            if ($item->platform == 1) {
                $result['platform'] = 'ios';
            } else {
                $result['platform'] = 'android';
            }
        }
        return $result;
    }

    private function _gen()
    {
        return '' . uniqid();
    }

    public function genToken($user_id, $app_id, $refresh_token = true)
    {
        $refresh_token = true;
        $result = false;
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        $criteria->addColumnCondition(array('client_id' => $app_id));
        $item = $this->getOwner()->find($criteria);
        if (!is_null($item)) {
            if ($refresh_token) {
                $item->access_token = $this->_gen();
                $item->client_id = $app_id;
                $item->save();
            }
            $result = $item->access_token;
        } else {

            $user = new UserToken;
            $user->user_id = $user_id;
            $user->client_id = $app_id;
            $user->access_token = $this->_gen();
            $user->save();
            $result = $user->access_token;
        }
        return $result;
    }

    //新的绑定方法
    public function newBind($user_id, $user_push_id, $platform, $client_id = 1)
    {
        $log = array();
        $log['user_id'] = $user_id;
        $log['user_push_id'] = $user_push_id;
        $log['platform'] = $platform;
        $log['client_id'] = $client_id;
        // file_put_contents(Yii::app()->getRuntimePath() . '/bind_' . date("Y_W") . '.txt', sprintf("%s %s %s", date("Y-m-d H:i:s"),json_encode($log), PHP_EOL), FILE_APPEND);
        if ($platform == 2) {
            $platform_text = 'android';
        } else if ($platform == 1) {
            $platform_text = 'ios';
        }
        $result = false;
        $bind_status = false;
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        $data = $this->getOwner()->findAll($criteria);
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                if ($value['client_id'] == $client_id) {
                    //更改pushID
                    if ($value['user_push_id'] != $user_push_id) {
                        //推送下线
                        $this->pushOff($value['user_push_id'], $value['client_id'], $value['platform']);
                        //
                    }
                    $value->user_push_id = $user_push_id;
                    $value->platform = $platform;
                    $value->is_bind = 1;
                    $value->client_id = $client_id;
                    $value->save();
                    $result = $bind_status = true;
                } else {
                    //解绑
                    //$value->is_bind = 0;
                    //$value = $bind_r->save();
                }
            }

        }
        if (!$bind_status) {
            //直接绑定
            $new_data = New UserToken;
            $new_data->user_id = $user_id;
            $new_data->user_push_id = $user_push_id;
            $new_data->platform = $platform;
            $new_data->is_bind = 1;
            $new_data->client_id = $client_id;
            $result = $new_data->save();
        }
        return $result;
    }

    //单推
    public function pushOff($user_push_id, $client_id, $platform, $data = array())
    {
        $reg_id = $user_push_id;
        $params = array();
        $custom = array();
        //推送消息提示登录。todo... 需要更换为 直接发送推送。而不是先添加到 消息列表
        //$msg_data['type'] = Message::TYPE_SYSTEM;
        $param['title'] = '用户在其它设备上登录';
        $param['detail'] = '用户在其它设备上登录';
        $param['description'] = '用户在其它设备上登录';
        $custom['msg_type'] = Message::MESSAGE_TYPE_COURIER_LOGIN_BY_OTHER;
        if ($platform == 1) {
            //ios 
            $is_push = 0;
            if ($client_id == 1) {
                $merchant_params['bundle'] = Config::model()->get('mi_push_package_name_xhup_ios');//小米推送包名IOS 跑男端 货主端
                $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhup_ios');//小米推送包名IOS 跑男端 
                // 测试标志, iOS一定要注意
                $push_component = new PushComponent($merchant_params, YII_DEBUG);
                $is_push = $push_component->pushToUserIos($reg_id, $param, $custom);
            } else {
                $merchant_params['bundle'] = Config::model()->get('mi_push_package_name_xhu_ios');//小米推送包名IOS 用户端 TMS端
                $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhu_ios');//小米推送包名IOS 用户端
                // 测试标志, iOS一定要注意
                $push_component = new PushComponent($merchant_params, YII_DEBUG);
                $is_push = $push_component->pushToUserIos($reg_id, $param, $custom);
            }

            $log_data = array();
            $log_data['platform'] = $platform;
            $log_data['merchant_params'] = $merchant_params;
            $log_data['reg_id'] = $reg_id;
            $log_data['param'] = $param;
            $log_data['custom'] = $custom;
            $log_data['is_push'] = $is_push;
            file_put_contents(Yii::app()->getRuntimePath() . '/push_message_' . date("Y_W") . '.txt', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($log_data), PHP_EOL), FILE_APPEND);

        } else {
            //Android 
            $is_push = 0;
            if ($client_id == 1) {
                $merchant_params['package'] = Config::model()->get('mi_push_package_name_xhup_android');//小米推送包名安卓 跑男端
                $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhup_android');//小米推送包名安卓 跑男端 // 测试标志, iOS一定要注意
                $push_component = new PushComponent($merchant_params, true);
                $is_push = $push_component->pushToUserAndroid($reg_id, $param, $custom);
            } else {
                $merchant_params['package'] = Config::model()->get('mi_push_package_name_xhu_android');//小米推送包名安卓 用户端
                $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhu_android');//小米推送包名安卓 用户端
                // 测试标志, iOS一定要注意
                $push_component = new PushComponent($merchant_params, true);
                $is_push = 0;
                $is_push = $push_component->pushToUserAndroid($reg_id, $param, $custom);
            }
            $log_data = array();
            $log_data['platform'] = $platform;
            $log_data['merchant_params'] = $merchant_params;
            $log_data['reg_id'] = $reg_id;
            $log_data['param'] = $param;
            $log_data['custom'] = $custom;
            $log_data['is_push'] = $is_push;
            file_put_contents(Yii::app()->getRuntimePath() . '/push_message_' . date("Y_W") . '.txt', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($log_data), PHP_EOL), FILE_APPEND);
        }
    }

    /*
    ***** from push
    */
    public function bind($user_id, $user_push_id, $platform, $client_id = 1)
    {
        $result = false;
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        $criteria->addColumnCondition(array('client_id' => $client_id));
        $bind_r = $this->getOwner()->find($criteria);
        $platform_text = '';
        if ($platform == 2) {
            $platform_text = 'android';
        } else if ($platform == 1) {
            $platform_text = 'ios';
        }
        if (!is_null($bind_r)) {
            $old_platform = $bind_r->platform;
            if ($user_push_id != $bind_r->user_push_id && !empty($bind_r->user_push_id) && $bind_r->is_bind) {
                $params = array();
                $custom = array();
                //推送消息提示登录。todo... 需要更换为 直接发送推送。而不是先添加到 消息列表
                //$msg_data['type'] = Message::TYPE_SYSTEM;
                $param['title'] = '用户在其它设备上登录';
                $param['detail'] = '用户在其它设备上登录';
                $param['description'] = '用户在其它设备上登录';
                $custom['msg_type'] = Message::MESSAGE_TYPE_COURIER_LOGIN_BY_OTHER;

                $single = true;
                //需要立即单推
                //TODO...   
                $merchant_params = array();
                $user_info = UserToken::model()->getPlatformByUserId($user_id);
                if (empty($user_info['platform']) || empty($user_info['push_user_id'])) {
                    return $result;
                }
                $reg_id = $bind_r->user_push_id;
                if ($old_platform == 1) {
                    //ios
                    $is_push = 0;
                    if ($bind_r->client_id == 1) {
                        $merchant_params['bundle'] = Config::model()->get('mi_push_package_name_xhup_ios');//小米推送包名IOS 跑男端 货主端
                        $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhup_ios');//小米推送包名IOS 跑男端
                        // 测试标志, iOS一定要注意
                        $push_component = new PushComponent($merchant_params, YII_DEBUG);
                        $is_push = $push_component->pushToUserIos($reg_id, $param, $custom);
                    } else {
                        $merchant_params['bundle'] = Config::model()->get('mi_push_package_name_xhu_ios');//小米推送包名IOS 用户端 TMS端
                        $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhu_ios');//小米推送包名IOS 用户端
                        // 测试标志, iOS一定要注意
                        $push_component = new PushComponent($merchant_params, YII_DEBUG);
                        $is_push = $push_component->pushToUserIos($reg_id, $param, $custom);
                    }

                    $log_data = array();
                    $log_data['user_id'] = $user_id;
                    $log_data['old_platform'] = $old_platform;
                    $log_data['merchant_params'] = $merchant_params;
                    $log_data['reg_id'] = $reg_id;
                    $log_data['param'] = $param;
                    $log_data['custom'] = $custom;
                    $log_data['is_push'] = $is_push;
                    file_put_contents(Yii::app()->getRuntimePath() . '/push_message_' . date("Y_W") . '.txt', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($log_data), PHP_EOL), FILE_APPEND);

                } else {
                    //Android
                    $is_push = 0;
                    if ($bind_r->client_id == 1) {
                        $merchant_params['package'] = Config::model()->get('mi_push_package_name_xhup_android');//小米推送包名安卓 跑男端
                        $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhup_android');//小米推送包名安卓 跑男端 // 测试标志, iOS一定要注意
                        $push_component = new PushComponent($merchant_params, true);
                        $is_push = $push_component->pushToUserAndroid($reg_id, $param, $custom);
                    } else {
                        $merchant_params['package'] = Config::model()->get('mi_push_package_name_xhu_android');//小米推送包名安卓 用户端
                        $merchant_params['secret'] = Config::model()->get('mi_push_secret_xhu_android');//小米推送包名安卓 用户端
                        // 测试标志, iOS一定要注意
                        $push_component = new PushComponent($merchant_params, true);
                        $is_push = 0;
                        $is_push = $push_component->pushToUserAndroid($reg_id, $param, $custom);
                    }
                    $log_data = array();
                    $log_data['user_id'] = $user_id;
                    $log_data['old_platform'] = $old_platform;
                    $log_data['merchant_params'] = $merchant_params;
                    $log_data['reg_id'] = $reg_id;
                    $log_data['client_id'] = $bind_r->client_id;
                    $log_data['param'] = $param;
                    $log_data['custom'] = $custom;
                    $log_data['is_push'] = $is_push;
                    file_put_contents(Yii::app()->getRuntimePath() . '/push_message_' . date("Y_W") . '.txt', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($log_data), PHP_EOL), FILE_APPEND);
                }

            }

            $bind_r->user_push_id = $user_push_id;
            $bind_r->platform = $platform;
            $bind_r->is_bind = 1;
            $bind_r->client_id = $client_id;
            $result = $bind_r->save();
        } else {
            $new_data = New UserToken;
            $new_data->user_id = $user_id;
            $new_data->user_push_id = $user_push_id;
            $new_data->platform = $platform;
            $new_data->is_bind = 1;
            $new_data->client_id = $client_id;
            $result = $new_data->save();

        }
        return $result;
    }

    public function unbind($user_id, $user_push_id, $client_id = 0)
    {
        $result = false;
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        $criteria->addColumnCondition(array('user_push_id' => $user_push_id));
        $criteria->addColumnCondition(array('is_bind' => 1));
        if (!empty($client_id)) {
            $criteria->addColumnCondition(array('client_id' => $client_id));
        }
        $bind_r = $this->getOwner()->find($criteria);
        if (!is_null($bind_r)) {
            $bind_r->is_bind = 0;
            $result = $bind_r->save();
        }
        return $result;
    }

    //添加 或者 新增 token 对应的用户ID
    public function addOrUpdate($token, $user_id)
    {
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('user_id' => $user_id));
        $old = $this->getOwner()->find($criteria);
        if (!empty($old)) {
            $old->access_token = $token;
            return $old->save();
        } else {
            $new_date = new UserToken;
            $new_date->access_token = $token;
            $new_date->user_id = $user_id;
            return $new_date->save();
        }
        return false;
    }
}

?>
